﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Text.RegularExpressions;

namespace UE.SharePoint.ImportExport
{
    /// <summary>
    /// Represents a common function when the sharepoint runtime.
    /// </summary>
    public static class Util
    {
        /// <summary>
        /// Validates whether the specified sharepoint list is existence.
        /// </summary>
        /// <param name="spWeb"></param>
        /// <param name="strSPListGuid"></param>
        /// <returns></returns>
        public static bool ValidateSPlistExist(SPWeb spWeb,string strSPListGuid)
        {
            strSPListGuid = strSPListGuid.Replace("{", "").Replace("}", "");
            if (!IsGuid(strSPListGuid)) // valid guid
            {
                return false;
            }

            Guid spListGuid= new Guid(strSPListGuid); ;
            SPList spList = null; 

            while (spWeb != null && spList == null)
            {
                try
                {
                    spList = spWeb.Lists[spListGuid];
                }
                catch
                {
                    spList = null;
                }

                spWeb = spWeb.ParentWeb;
            }

            return spList != null;
        }

        /// <summary>
        /// Validates whether the specified string is categorized as guid. 
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsGuid(string str)
        {
            Match m = Regex.Match(str, @"^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$", RegexOptions.IgnoreCase);
            return m.Success;
        }
    }
}